<?php

namespace App\Services\QCloud;

/**
 * 腾讯云服务
 *
 * Class QCloud
 * @package App\Services\QCloud
 */
class QCloud
{
    protected $config;
    
    protected $appId;
    
    protected $tlsSig;
    
    public function __construct()
    {
        $this->config = config('services.qcloud');
        
        $this->appId = $this->config['app_id'];
    }
    
    /**
     * 生成视频加密签名 sig
     *
     * @param int $roomId
     * @param int $expired
     * @param string $version 版本号
     * @return string|null
     */
    public function genRoomSig($roomId, $expired, $version = '2')
    {
        // 权限密钥
        $key = $this->config['secret'];
        
        $cmd = __DIR__ . "/tea_encode {$key} {$version} {$this->appId} {$roomId} {$expired}";
        exec($cmd, $output, $status);
        
        if ($status != 0) {
            return null;
        }
        
        return $output[0];
    }
    
    /**
     * TLSSig API
     *
     * @return TLSSig
     */
    public function getTLSSig()
    {
        if (! isset($this->tlsSig)) {
            $this->tlsSig = new TLSSig($this->appId, $this->config['keys_path']);
        }
        
        return $this->tlsSig;
    }
    
    /**
     * 生成 user sig，有效期为1年
     *
     * @param string $identifier
     * @return string
     *
     * @throws \Exception
     */
    public function genUserSig($identifier)
    {
        return $this->getTLSSig()->genSig($identifier);
    }
    
    /**
     * 获取流地址
     *
     * @param string $roomId
     * @param string $liveOpenId
     * @param string $type 摄像头数据类型是main，屏幕分享的数据类型是aux
     * @return array
     */
    public function getStreamAddress($roomId, $liveOpenId, $type = 'main')
    {
        // 直播码
        $liveCode = md5("{$roomId}_{$liveOpenId}_{$type}");
        $bizId = $this->config['bizid'];
        
        return [
            'rtmp' => "rtmp://{$bizId}.liveplay.myqcloud.com/live/{$bizId}_{$liveCode}",
            'flv' => "http://{$bizId}.liveplay.myqcloud.com/live/{$bizId}_{$liveCode}.flv",
            'hls' => "http://{$bizId}.liveplay.myqcloud.com/live/{$bizId}_{$liveCode}.m3u8",
        ];
    }
}
